import os,base64
from PIL import Image
from io import BytesIO
from time import sleep
from support.stream.bilibilistreaming import BiliStreaming
from support.utils.toolkit import Log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
 
class Bilibili:
    LOGIN_URL = "https://passport.bilibili.com/login"
    LOGIN_RESULT_CHECK_URL = "https://www.bilibili.com/"

    def __init__(self, *, hubaddr, hubport=4444):
        options = Options()
        options.add_argument("--start-maximized")
        self.driver = webdriver.Remote('http://{}:{}/wd/hub'.format(hubaddr, hubport), options=options)
        self.loggedIn = False

    def close(self):
        self.driver.quit()

    def saveLoginQR(self, element):
        base64_data = element.get_attribute("src")
        with open(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "bqr.base64"), 'w') as file:
            file.write(base64_data)

    def removeLoginQR(self):
        file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "bqr.base64")
        if(os.path.exists(file)):
            os.remove(file)

    def login(self, *, url = LOGIN_URL, expected_url=LOGIN_RESULT_CHECK_URL):
        self.driver.get(url)
        while(self.driver.current_url != expected_url):
            self.loggedIn = False
            qrlist = self.driver.find_elements(By.XPATH, '//div[@class="login-scan__qrcode"]//img')
            if(len(qrlist) == 1):
                Log.i("Waiting for scan to login")
                self.saveLoginQR(qrlist[0])
                sleep(60)
            if(self.driver.current_url == expected_url):
                self.loggedIn = True
                break
            self.driver.get(url)
        self.removeLoginQR()

    def isLoggedIn(self):
        return self.loggedIn
    
    def getCookie(self):
        cookies = self.driver.get_cookies()
        info = ""
        for cookie in cookies:
            info += "{}={};".format(cookie["name"], cookie["value"])
        return info
